package com.jy.it.ui.admin;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import com.jy.it.entity.Admin;
import com.jy.it.entity.Rule;
import com.jy.it.service.RuleService;
import com.jy.it.service.WzService;
import com.jy.it.service.impl.WzServiceImpl;





@Controller
public class WzController {
	@Autowired
    private RuleService ruleService=null;
	@Autowired
	private WzService wzService=null;
	@RequestMapping(value="/wz/add",method=RequestMethod.GET)
	public String add(Model m) {
	
		List<Rule> rules=ruleService.findAll();
		m.addAttribute("rules",rules);
		return "admin/admin_wz_add";
	}
	@RequestMapping(value="/wz/add",method=RequestMethod.POST)
	public String add(String carno
			,@DateTimeFormat(pattern="yyyy-MM-dd HH:mm") Date wztime//接受日期类型，需要用注解设定日期格式
			,int ruleid
			,String wzaddress
			,String remark
			,MultipartFile photoFile
			,HttpServletRequest req
			,HttpSession session
			,Model m
			) throws IllegalStateException, IOException {
		Admin admin=(Admin) session.getAttribute("admin");//获取当前管理员用户，插入数据库要用
		String imgname=null;
		if(!photoFile.isEmpty()) {
			String prjdir=req.getServletContext().getRealPath("/");
			String webapps=new File(prjdir).getParent();
			String ext=photoFile.getOriginalFilename().substring(photoFile.getOriginalFilename().lastIndexOf("."));
			imgname=UUID.randomUUID().toString()+ext;
			if(new File(webapps+"/imgs/wz/").exists()==false) 
				new File(webapps+"/imgs/wz/").mkdirs();
			
			photoFile.transferTo(new File(webapps+"/imgs/wz/"+imgname));
		}
		//准备下拉数据
		int n=wzService.add(carno,ruleid,wzaddress,wztime,imgname,remark,admin.getId());
		if(n==0) {//插入不成功，则提示错误，重新录入
			m.addAttribute("err","无此车牌号码");
			return "admin/admin_wz_add";
		}
		m.addAttribute("success","ok");//添加成功，传信息到页面提示
		return "redirect:/wz/add";
	}
}
